﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MaciejGrabek.WP7.Services.Model.Entities;
using MaciejGrabek.WP7.Services.Model.Mappers;

namespace MaciejGrabek.WP7.Services.Model.Repositories
{
    public class GameResultsRepository : IGameResultsRepository
    {
        GameServicesDBEntities db = new GameServicesDBEntities();

        public IEnumerable<GameResultLightDto> GetGameResults(string gameNormalizedName)
        {
            int gameId = GetGameIdFromName(gameNormalizedName);
            var items = db.GameResultsLightView.Where(item => item.GameId == gameId).Select(item => item);
            return GameResultLightMapper.ToDto(items);
        }

        public void SetGameResult(GameResultDto value)
        {
            value.GameId = GetGameIdFromHash(value.GameHash);
            if (value.GameId > 0)
            {
                GameResult result = GameResultMapper.FromDto(value);
                GameServicesDBEntities db = new GameServicesDBEntities();
                GameResult existing = db.GameResult.Where(item => (item.DeviceId == result.DeviceId && item.GameId == result.GameId)).Select(item => item).SingleOrDefault();
                if (existing != null)
                {
                    existing.Score = result.Score;
                }
                else
                {
                    db.GameResult.AddObject(result);
                }

                db.SaveChanges();
            }
        }

        public IEnumerable<GameDto> GetGames()
        {
            var items = db.Games.Select(game => game);
            return GameMapper.ToDto(items);
        }

        private int GetGameIdFromName(string gameNormalizedName)
        {
            int gameId = db.Games.Where(g => g.NormalizedName.ToLower() == gameNormalizedName.ToLower()).Select(g => g.Id).FirstOrDefault();
            return gameId;
        }

        private int GetGameIdFromHash(string gameHash)
        {
            int gameId = db.Games.Where(g => g.GameHash.ToLower() == gameHash.ToLower()).Select(g => g.Id).FirstOrDefault();
            return gameId;
        }
    }
}
